<template>
  <el-card header="新建商家">
    <div style="width: 80%; margin: auto;">
      <el-steps :active="active" finish-status="success">
        <el-step title="商品信息"></el-step>
        <el-step title="规格库存"></el-step>
        <el-step title="完成创建"></el-step>
      </el-steps>
      <el-form label-position="right"
               ref="form"
               status-icon
               :model="itemInfo"
               :rules="itemInfoRule"
               label-width="100px"
               style="margin-top: 20px">
        <div v-show="active === 0">
          <el-form-item label="商品图片" prop="imgList">
            <el-upload
              action="https://api.sc-edu.com/tool/upimg/"
              name="Img"
              :on-success="fileSuccess"
              :on-remove="fileRemove"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-form-item>
          <el-form-item label="商品名称" prop="name">
            <el-input placeholder="请输入商品名称" v-model="itemInfo.name"></el-input>
          </el-form-item>
          <el-form-item label="商品编号" prop="code">
            <el-input placeholder="请输入商品编号" v-model="itemInfo.code"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="categoryId">
            <el-tree
              :data="tags"
              :props="{label: 'name'}"
              node-key="id"
              accordion
              highlight-current
              ref="tree"
              :check-strictly="true"
              show-checkbox
              @check-change="nodeCheck"
              :expand-on-click-node="false">
            </el-tree>
          </el-form-item>
          <el-form-item label="商品价格" prop="price">
            <el-input-number type="number" :step="step" :precision="precision" placeholder="请输入商品价格" v-model="itemInfo.price"></el-input-number>
          </el-form-item>
          <el-form-item label="商品活动价" prop="promotionPrice">
            <el-input-number type="number" :step="step" :precision="precision" placeholder="请输入商品活动价格" v-model="itemInfo.promotionPrice"></el-input-number>
          </el-form-item>
          <el-form-item label="商品简介">
            <el-input v-model="itemInfo.intro"></el-input>
          </el-form-item>
          <el-form-item label="商品介绍">
            <VueEditor v-model="itemInfo.desc"
                       @imageAdded="handleImageAdded">
            </VueEditor>
          </el-form-item>
        </div>
        <div v-show="active === 1">
          <el-form label-position="right"
                   status-icon
                   label-width="50px"
                   style="margin-top: 20px">
            <div style="display: flex; justify-content: space-between" class="spec" v-for="(item, index) in specList" :key="index">
              <el-form-item label="型号">
                <el-input placeholder="请输入型号" readonly :value="item.spec"></el-input>
              </el-form-item>
              <el-form-item label="库存">
                <el-input-number readonly :value="item.num"></el-input-number>
              </el-form-item>
              <el-form-item label="价格">
                <el-input-number readonly :value="item.price"></el-input-number>
              </el-form-item>
              <el-form-item>
                <el-button icon="el-icon-delete" type="danger" @click="delSpec(index)">删除型号</el-button>
              </el-form-item>
            </div>
          </el-form>
          <el-form label-position="right"
                   status-icon
                   label-width="50px"
                   style="margin-top: 20px">
            <div style="display: flex; justify-content: space-between" class="spec">
              <el-form-item label="型号" >
                <el-input placeholder="请输入型号" v-model="specInfo.spec"></el-input>
              </el-form-item>
              <el-form-item label="库存">
                <el-input-number :precision="0" :step="1" :min="0" v-model="specInfo.num"></el-input-number>
              </el-form-item>
              <el-form-item label="价格">
                <el-input-number :precision="2" :step="0.01" :min="0" v-model="specInfo.price"></el-input-number>
              </el-form-item>
              <el-form-item>
                <el-button icon="el-icon-circle-plus-outline" @click="addSpec">添加型号</el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div v-show="active === 3" style="display: flex; justify-content: center; padding: 30px">
          <img src="../../assets/h5/success.png">
        </div>
      </el-form>
      <div style="text-align: center">
        <!--<el-button v-if="active > 0 && active < 3" @click="previous" >上一步</el-button>-->
        <el-button v-if="active <= 2" @click="nextStep">下一步</el-button>
        <el-button v-if="active === 3" @click="finish" type="primary" style="width: 40%; max-width: 120px">完成</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
  import { VueEditor } from "vue2-editor";
  import {getAllCategory, addItems, addItemSpec} from "../../api/item";
  import axios from 'axios';

  export default {
    name: "create",
    components: {
      VueEditor
    },
    data() {
      return {
        precision: 2,
        step: 0.01,
        active: 0,
        dialogImageUrl: '',
        dialogVisible: false,
        tags: [],
        defaultProps: null,
        selectOrg: {
          orgsid: []
        },
        itemInfo: {
          code: '',
          desc: '',
          intro: '',
          categoryId: '',
          imgList: [],
          name: '',
          price: '',
          promotionPrice: ''
        },
        itemInfoRule: {
          code: [{required: true, message: '请输入信息'}],
          desc: [{required: true, message: '请输入信息'}],
          intro: [{required: true, message: '请输入信息'}],
          categoryId: [{required: true, message: '请输入信息'}],
          imgList: [{required: true, message: '请输入信息'}],
          name: [{required: true, message: '请输入信息'}],
          price: [{required: true, message: '请输入信息'}],
          promotionPrice: [{required: true, message: '请输入信息'}]
        },
        specList: [],
        specInfo: {
          spec: '',
          num: '',
          price: ''
        },
        goodId: 0,
      }
    },
    methods: {
      previous: function () {
        this.active -= 1;
        if (this.active === 2) {
          this.active -= 1;
        }
      },
      async nextStep() {
        if (this.active === 0) {
          await this.addItem();
        }
        if (this.active === 1) {
          await this.finishSpec()
        }
        this.active += 1;
        if (this.active === 2) {
          this.active += 1;
        }
      },
      finish: function () {
        this.$router.push('/item')
      },
      fileSuccess(response, file, fileList) {
        this.itemInfo.imgList = [];
        fileList.map(v => {
          this.itemInfo.imgList.push(v.response.data.url);
        })
      },
      fileRemove(file, fileList) {
        this.itemInfo.imgList = [];
        fileList.map(v => {
          this.itemInfo.imgList.push(v.response.data.url);
        })
      },
      handleImageAdded: function(file, Editor, cursorLocation, resetUploader) {
        var fd = new FormData();
        fd.append('Img', file);

        axios({
          url: 'https://api.sc-edu.com/tool/upimg/',
          method: 'POST',
          headers: {'Content-Type': 'multipart/form-data'},
          data: fd,
          transformRequest: [
            (data) => {
              return data
            }
          ]
        })
          .then((result) => {
            let url = result.url; // Get url from response
            Editor.insertEmbed(cursorLocation, 'image', url);
            resetUploader();
          })
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      async getAllCategory() {
        let res = await getAllCategory();
        let tags = [];
        res.categories.map(v => {
          if (v.parentId === 0) {
            v.children = [];
            let id = v.id;
            res.categories.map(vv => {
              if (vv.parentId === id) {
                vv.children = [];
                let sid = vv.id;
                res.categories.map(vvv => {
                  if (vvv.parentId === sid) {
                    vvv.level = 3;
                    vvv.disabled = false;
                    vv.children.push(vvv)
                  }
                });
                vv.level = 2;
                vv.disabled = true;
                v.children.push(vv)
              }
            });
            v.level = 1;
            v.disabled = true;
            tags.push(v)
          }
        });
        this.tags = tags;
      },
      nodeCheck(data, checked, indeterminate) {
        const indexs = this.selectOrg.orgsid.indexOf(data.id)
        // 如果不存在数组中，并且数组中已经有一个id并且checked为true的时候，代表不能再次选择。
        if (indexs < 0 && this.selectOrg.orgsid.length === 1 && checked) {
          this.$message({
            message: '只能选择一个区域！',
            type: 'error',
            showClose: true
          })
          // 设置已选择的节点为false 很重要
          this.$refs.tree.setChecked(data, false)
        } else if (this.selectOrg.orgsid.length === 0 && checked) {
          // 发现数组为空 并且是已选择
          // 防止数组有值，首先清空，再push
          this.selectOrg.orgsid = [];
          this.itemInfo.categoryId = data.id;
          this.selectOrg.orgsid.push(data.id)
        } else if (
          indexs >= 0 &&
          this.selectOrg.orgsid.length === 1 &&
          !checked
        ) {
          // 再次直接进行赋值为空操作
          this.itemInfo.categoryId = 0;
          this.selectOrg.orgsid = []
        }
      },
      addSpec() {
        if (!this.specInfo.spec) {
          this.$message.error('请输入规格');
          return;
        }
        if (!this.specInfo.price) {
          this.$message.error('请输入价格');
          return;
        }
        if (!this.specInfo.num) {
          this.$message.error('请输入库存数量');
          return;
        }
        this.specList.push({
          spec: this.specInfo.spec,
          num: this.specInfo.num,
          price: this.specInfo.price
        });
        this.specInfo = {
          spec: '',
          num: '',
          price: ''
        }
      },
      delSpec(index) {
        this.specList.splice(index, 1);
      },
      finishSpec() {
        this.specList.map(v => {
          let data = {
            goodsId: this.goodId,
            price: v.price.toFixed(2) * 100,
            specValue: v.spec,
            stockNum: v.num,
          }
          addItemSpec(data)
        })
      },
      async addItem() {
        let data = {
          code: this.itemInfo.code,
          description: this.itemInfo.intro,
          goodsCategoryId: this.itemInfo.categoryId,
          imgList: this.itemInfo.imgList.join(','),
          name: this.itemInfo.name,
          detail: this.itemInfo.desc
        }
        let res = await addItems(data);
        this.goodId = res.newGoodId
      }
    },
    created() {
      this.getAllCategory();
    }
  }
</script>


<style scoped>
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
</style>
